/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.user.web.controller;

import co.yixiang.annotation.AnonymousAccess;
import co.yixiang.aop.log.Log;
import co.yixiang.common.api.ApiResult;
import co.yixiang.common.web.controller.BaseController;
import co.yixiang.constant.ShopConstants;
import co.yixiang.modules.order.service.YxStoreOrderService;
import co.yixiang.modules.order.web.dto.InvestOrderCountDTO;
import co.yixiang.modules.order.web.dto.OrderCountDTO;
import co.yixiang.modules.shop.entity.YxInvestCustomer;
import co.yixiang.modules.shop.entity.YxSales;
import co.yixiang.modules.shop.entity.YxStoreProduct;
import co.yixiang.modules.shop.service.*;
import co.yixiang.modules.shop.service.impl.YxInvestOrderServiceImpl;
import co.yixiang.modules.shop.service.impl.YxSalesServiceImpl;
import co.yixiang.modules.shop.web.param.YxInvestOrderQueryParam;
import co.yixiang.modules.shop.web.param.YxSalesCommissionDetailQueryParam;
import co.yixiang.modules.shop.web.param.YxStoreProductQueryParam;
import co.yixiang.modules.shop.web.vo.YxInvestOrderQueryVo;
import co.yixiang.modules.shop.web.vo.YxSalesCommissionDetailQueryVo;
import co.yixiang.modules.shop.web.vo.YxSalesManageQueryVo;
import co.yixiang.modules.user.entity.YxUser;
import co.yixiang.modules.user.service.YxSystemUserLevelService;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.YxUserSignService;
import co.yixiang.modules.user.web.param.UserEditParam;
import co.yixiang.modules.user.web.param.YxUserSignQueryParam;
import co.yixiang.modules.user.web.vo.YxSystemUserLevelQueryVo;
import co.yixiang.modules.user.web.vo.YxUserQueryVo;
import co.yixiang.service.dto.ScanCodePay;
import co.yixiang.service.impl.KryConfigServiceImpl;
import co.yixiang.utils.SecurityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 用户控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-10-16
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "用户中心", tags = "投资端:用户中心", description = "用户中心")
public class UserController extends BaseController {

    private final YxUserService yxUserService;
    private final YxStoreOrderService orderService;
    private final YxStoreProductRelationService relationService;

    private final YxInvestOrderService yxInvestOrderServiceImpl;
    private final YxSalesCommissionDetailService yxSalesCommissionDetailService;
    private final YxStoreProductService storeProductService;
    private final YxInvestOrderService yxInvestOrderService;
    private final YxInvestCustomerService yxInvestCustomerService;
    private final YxSalesService yxSalesService;
    private final YxSystemConfigService yxSystemConfigService;
    private final YxSalesManageService yxSalesManageService;
    private final PasswordEncoder passwordEncoder;
    private final KryConfigServiceImpl kryConfigService;

    /**
     * 订单统计数据
     */
    @GetMapping("/order/data")
    @ApiOperation(value = "订单统计数据", notes = "订单统计数据")
    public ApiResult<InvestOrderCountDTO> orderData() {
        int uid = SecurityUtils.getUserId().intValue();
        YxSales yxSales = yxSalesService.getById(uid);
        List<YxSalesManageQueryVo> saleList = null;
        List<Integer>  saleIdList = null;
        if(yxSales.getGroupId() == 2){
            //如果是经理，查询他负责的业务员
            saleList = yxSalesManageService.getListByManagerId(yxSales.getUid());
            if(saleList != null && saleList.size() > 0){
                saleIdList = new ArrayList<>();
                for(YxSalesManageQueryVo yxSalesManageQueryVo : saleList){
                    saleIdList.add(yxSalesManageQueryVo.getUid());
                }
            }
        }

        //1.普通业务员   2.经理   3集团员工  4总监
        int productLockMaxCount = 0;
        if(yxSales.getGroupId() == 1){
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_sales"));
        }
        else if(yxSales.getGroupId() == 2 ){
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_handle"));
        }
        else if(yxSales.getGroupId() == 3){
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_group"));
        }
        else if(yxSales.getGroupId() == 4){
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_manager"));
         }
         //个人数据
         InvestOrderCountDTO investOrderCountDTO = yxInvestOrderServiceImpl.orderData(uid);
        //团队的数据
        if(yxSales.getGroupId() != 1 && yxSales.getGroupId() != 3){

            InvestOrderCountDTO investOrderCountDTOTeam = yxInvestOrderServiceImpl.orderDataTeam(uid,  saleIdList );
            investOrderCountDTO.setAuditedCountTeam(investOrderCountDTOTeam.getAuditedCount());
            investOrderCountDTO.setCancelCountTeam(investOrderCountDTOTeam.getCancelCount());
            investOrderCountDTO.setCommissionCountTeam(investOrderCountDTOTeam.getCommissionCount());
            investOrderCountDTO.setCustomerCountTeam(investOrderCountDTOTeam.getCustomerCount());
            investOrderCountDTO.setEndCountTeam(investOrderCountDTOTeam.getEndCount());
            investOrderCountDTO.setUnpaidCountTeam(investOrderCountDTOTeam.getUnpaidCount());
            investOrderCountDTO.setUnpaidEndCountTeam(investOrderCountDTOTeam.getUnpaidEndCount());
            investOrderCountDTO.setOrderCountMonthTeam(investOrderCountDTOTeam.getOrderCountMonth());
            investOrderCountDTO.setSumPriceMonthTeam(investOrderCountDTOTeam.getSumPriceMonth());
            investOrderCountDTO.setUnAuditCountTeam(investOrderCountDTOTeam.getUnAuditCountTeam());

        }

        investOrderCountDTO.setProductLockMaxCount(productLockMaxCount);

        if(yxSales.getGroupId()  == 2){

            investOrderCountDTO.setSaleCountTeam(yxSalesManageService.getListByManagerId(uid).size());

        }
        else if(yxSales.getGroupId()  == 4){
            investOrderCountDTO.setSaleCountTeam(yxSalesService.getAll().size());
        }
        return ApiResult.ok(investOrderCountDTO);
    }

    /**
     * 获取收藏产品
     */
    @GetMapping("/productLock/user")
    @ApiOperation(value = "保留的商品列表", notes = "保留的商品列表")
    public ApiResult<Object> productLockUser(YxStoreProductQueryParam productQueryParam) {
        int uid = SecurityUtils.getUserId().intValue();
        List<YxSalesManageQueryVo> saleList = null;
        YxSales yxSales = yxSalesService.getById(uid);
        List<Integer>  saleIdList = null;
        if(yxSales.getGroupId() == 2){
            //如果是经理，查询他负责的业务员
            saleList = yxSalesManageService.getListByManagerId(yxSales.getUid());
            if(saleList != null && saleList.size() > 0){
                saleIdList = new ArrayList<>();
                for(YxSalesManageQueryVo yxSalesManageQueryVo : saleList){
                    saleIdList.add(yxSalesManageQueryVo.getUid());
                }
            }
        }
        if(yxSales.getGroupId() == 4){
            uid = 0;
        }
        return ApiResult.ok(storeProductService.getLockProductList(productQueryParam ,uid,saleIdList));
    }

    /**
     * 业务员提成
     */
    @GetMapping("/user/commission")
    @ApiOperation(value = "认购提成(个人)", notes = "认购提成(个人)")
    public ApiResult<Object> userCommission(YxSalesCommissionDetailQueryParam yxSalesCommissionDetailQueryParam) {
        int uid = SecurityUtils.getUserId().intValue();
        Map<String, Object> map = new LinkedHashMap<>();
        List<YxSalesCommissionDetailQueryVo> commissionList= yxSalesCommissionDetailService.userCommission(uid,yxSalesCommissionDetailQueryParam,null);
        BigDecimal commissionCount  = new BigDecimal(0);
        for(YxSalesCommissionDetailQueryVo yxSalesCommissionDetailQueryVo : commissionList) {
            double investPrice = yxSalesCommissionDetailQueryVo.getInvestPrice();
            commissionCount.add(new BigDecimal(investPrice));
        }
        map.put("orderCount", commissionList.size());
        map.put("commissionCount", commissionCount.toString());
        map.put("commissionList", commissionList);
        return ApiResult.ok(map);
    }

    /**
     * 业务员提成
     */
    @GetMapping("/teamUser/commission")
    @ApiOperation(value = "认购提成(团队)", notes = "认购提成(团队)")
    public ApiResult<Object> teamUserCommission(YxSalesCommissionDetailQueryParam yxSalesCommissionDetailQueryParam) {
        int uid = SecurityUtils.getUserId().intValue();
        YxSales yxSales = yxSalesService.getById(uid);
        List<YxSalesManageQueryVo> saleList = yxSalesManageService.getListByManagerId(yxSales.getUid());
        List<Integer>  saleIdList = null;
        if(saleList != null && saleList.size() > 0){
            saleIdList = new ArrayList<>();
            for(YxSalesManageQueryVo yxSalesManageQueryVo : saleList){
                saleIdList.add(yxSalesManageQueryVo.getUid());
            }
        }

        else if(yxSales.getGroupId() == 4){
            uid =0;
        }

        if(yxSalesCommissionDetailQueryParam.getSalesId() != -1){
            uid = yxSalesCommissionDetailQueryParam.getSalesId();
        }
        Map<String, Object> map = new LinkedHashMap<>();
        List<YxSalesCommissionDetailQueryVo> commissionList= yxSalesCommissionDetailService.userCommission(uid,yxSalesCommissionDetailQueryParam,saleIdList);
        BigDecimal commissionCount  = new BigDecimal(0);
        for(YxSalesCommissionDetailQueryVo yxSalesCommissionDetailQueryVo : commissionList) {
            double investPrice = yxSalesCommissionDetailQueryVo.getInvestPrice();
            commissionCount.add(new BigDecimal(investPrice));
        }
        map.put("orderCount", commissionList.size());
        map.put("commissionCount", commissionCount.toString());
        map.put("commissionList", commissionList);
        return ApiResult.ok(map);
    }


    /**
     * 业务员列表
     */
    @GetMapping("/user/saleList")
    @ApiOperation(value = "业务员列表", notes = "业务员列表")
    public ApiResult<List<YxSalesManageQueryVo>> saleList() {
        int uid = SecurityUtils.getUserId().intValue();
        YxSales yxSales = yxSalesService.getById(uid);
        List<YxSalesManageQueryVo> saleList = null;
        //总监
        if(yxSales.getGroupId() == 4 ){
            saleList = yxSalesManageService.getAllSales();
        }
        else if(yxSales.getGroupId() == 2){
            saleList = yxSalesManageService.getListByManagerId(yxSales.getUid());

        }


        return ApiResult.ok(saleList);
    }


    /**
     * 订单列表
     */
    @Log(value = "客户订单列表",type = 1)
    @GetMapping("/user/invest/orderList")
    @ApiOperation(value = "客户订单列表",notes = "客户订单列表")
    public ApiResult<List<YxInvestOrderQueryVo>> investOrderList(YxInvestOrderQueryParam queryParam){

        Map<String, Object> map = new LinkedHashMap<>();
        int uid = SecurityUtils.getUserId().intValue();
         YxInvestCustomer customer = yxInvestCustomerService.getById(queryParam.getCustomerId());


        map.put("orderList", yxInvestOrderService.orderList(uid,customer.getInvestPhone(),queryParam.getType(),
                queryParam.getPage().intValue(),queryParam.getLimit().intValue()));

        map.put("customerInfo",customer);
         return ApiResult.ok(map);
    }

    /**
     * 获取收藏产品
     */
    @GetMapping("/collect/user")
    @ApiOperation(value = "获取收藏产品", notes = "获取收藏产品")
    public ApiResult<Object> collectUser(@RequestParam(value = "page", defaultValue = "1") int page,
                                         @RequestParam(value = "limit", defaultValue = "10") int limit) {
        int uid = SecurityUtils.getUserId().intValue();
        return ApiResult.ok(relationService.userCollectProduct(page, limit, uid , "collect"));
    }

    /**
     * 获取浏览商品
     */
    @GetMapping("/browse/history")
    @ApiOperation(value = "获取浏览商品", notes = "获取浏览商品")
    public ApiResult<Object> browseHistory(@RequestParam(value = "page", defaultValue = "1") int page,
                                         @RequestParam(value = "limit", defaultValue = "10") int limit) {
        int uid = SecurityUtils.getUserId().intValue();
        return ApiResult.ok(relationService.userCollectProduct(page, limit, uid , "browse"));
    }

    /**
     * 修改密码
     */
    @GetMapping("/usr/updatePassword")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public ApiResult<Object> updatePassword(@RequestParam(value = "oldPassword", defaultValue = "") String oldPassword,
                                         @RequestParam(value = "newPassword", defaultValue = "") String newPassword) {
        int uid = SecurityUtils.getUserId().intValue();
        YxSales yxSales = yxSalesService.getById(uid);
        String password = passwordEncoder.encode(newPassword);
//
//        if(!yxSales.getPassword().equals(password)){
//            return ApiResult.fail("旧密码不正确");
//        }
            yxSales.setPassword(password);
            yxSales.setPwdPlaintext(newPassword);
            yxSalesService.updateById(yxSales);

        return ApiResult.ok("success");
    }


    /**
     * 修改密码
     */
    @GetMapping("/usr/updateSecondPwdOpen")
    @ApiOperation(value = "二次密码校验开关", notes = "二次密码校验开关")
    public ApiResult<Object> updateSecondPwdOpen(@RequestParam(value = "secondPwdOpen", defaultValue = "0") String secondPwdOpen
                                           ) {
        int uid = SecurityUtils.getUserId().intValue();
        YxSales yxSales = yxSalesService.getById(uid);
        yxSales.setSecondPwdOpen(Integer.parseInt(secondPwdOpen));
        yxSalesService.updateById(yxSales);

        return ApiResult.ok("success");
    }



}

